package com.mall.b2c.service.impl;

import com.mall.b2c.bean.IntergralShopOrderBean;
import com.mall.b2c.dao.IntergralDao;
import com.mall.b2c.dao.IntergralOrderDao;
import com.mall.b2c.dao.MemberDao;
import com.mall.b2c.dao.ShopCartItemDao;
import com.mall.b2c.domain.delivery.DeliveryMethodDomain;
import com.mall.b2c.domain.intergral.IntergralDomain;
import com.mall.b2c.domain.intergral.ShopCartItemDomain;
import com.mall.b2c.domain.intergral.ShopOrderDomain;
import com.mall.b2c.domain.intergral.ShopProductDomain;
import com.mall.b2c.domain.member.MemberDomain;
import com.mall.b2c.domain.store.StoreDomain;
import com.mall.b2c.enums.IntergralLogType;
import com.mall.b2c.enums.IntergralOrderStatus;
import com.mall.b2c.service.*;
import com.mall.b2c.util.SerialNumberUtil;
import com.mall.common.bean.Message;
import com.mall.common.bean.Order;
import com.mall.common.exception.NoticeException;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.impl.BaseServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.hsqldb.lib.HashMap;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.LockModeType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by chen on 16/12/15.
 */
@Service
@Transactional
public class IntergralOrderServiceImpl extends  BaseServiceImpl<ShopOrderDomain, Long> implements IntergralOrderService {

    @Resource
    IntergralShopClassService intergralShopClassService;
    @Resource
    IntergralShopProductService intergralShopProductService;
    @Resource
    IntergralService intergralService;
    @Resource
    MemberService memberService;

    @Resource
    StoreService storeService;

    @Resource private MemberDao memberDao;
    @Resource private ShopCartItemDao shopCartItemDao;

    @Resource
    public void setBaseDao(IntergralOrderDao intergralorderDao) {
        super.setBaseDao(intergralorderDao);
    }
    public List<Map<String, Object>> findList(Date startDate, Date endDate){
        Finder finder = Finder.create("select shopOrder.id,shopOrder.store.name as name,sum(shopOrder.intergral) as price from ShopOrderDomain shopOrder left join shopOrder.product left join shopOrder.store where 1=1");
        if(startDate != null){
            finder.append(" and shopOrder.createDate >= :startDate");
            finder.setParam("startDate", startDate);
        }
        if(endDate != null){
            finder.append(" and shopOrder.createDate <= :endDate");
            finder.setParam("endDate", endDate);
        }
        finder.append(" group by shopOrder.store.id");
        List rows = finder.findHQLList();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (Object row : rows) {
            Object[] cells = (Object[]) row;
            Map<String,Object> map = new java.util.HashMap<>();
            map.put("id",cells[0]);
            map.put("name",cells[1]);
            map.put("price",cells[2]);
           list.add(map);
        }

        return list;

    }





    @Transactional(propagation= Propagation.REQUIRED)
    public Message exchange(IntergralShopOrderBean orderBean){
        ShopProductDomain productDomain = intergralShopProductService.find(orderBean.getProductId());
      /* IntergralDomain intergralDomain =  intergralService.getByMemberId(orderBean.getMemberId());
        MemberDomain memberDomain = intergralDomain.getMember();*/
        //计算出所使用积分
        int price = productDomain.getPrice()*orderBean.getNum();

        MemberDomain member = memberService.find(orderBean.getMemberId());
       /* [#elseif member.point gte 100000]钻石会员
                [#elseif member.point gte 50000 && member.point < 100000]黄金会员*/
        Integer point = member.getPoint();
        if(point != null && point >= 50000 && point < 100000 ){
            //7折
            price = Math.round(price*7/10);
        }  else if(point != null && point >= 100000){
            //7折
            price = Math.round(price*8/10);
        }

        //用户扣除积分  记录日志
        intergralService.alterations(orderBean.getMemberId(), price, IntergralLogType.reducenum, "购买" + productDomain.getName() + "扣除用户积分");
        //商品减少数量
        intergralShopProductService.exchange(productDomain, orderBean.getNum());


      //  StoreDomain domain = storeService.find();

        //记录订单
        ShopOrderDomain shopOrderDomain = new ShopOrderDomain();
        shopOrderDomain.setOrderNo(SerialNumberUtil.buildOrderNo());
        shopOrderDomain.setNum(orderBean.getNum());
        shopOrderDomain.setMember(member);
        shopOrderDomain.setStatus(IntergralOrderStatus.unsend);
        shopOrderDomain.setIntergral(price);
        shopOrderDomain.setProduct(productDomain);
        shopOrderDomain.setMember(member);
        shopOrderDomain.setPhone(orderBean.getPhone());
        shopOrderDomain.setName(orderBean.getName());
        shopOrderDomain.setAddress(orderBean.getAddress());
        shopOrderDomain.setStore(storeService.find(orderBean.getStoreId()));

        persist(shopOrderDomain);
        return Message.success("操作成功",null);

    }


    public List<IntergralShopOrderBean> getOrderList(Long userId,String orderBy){
        Finder finder = Finder.create("select new com.mall.b2c.bean.IntergralShopOrderBean(bean) from ShopOrderDomain bean ");
        if(userId!=null){
            finder.append(" where bean.member.id = (:id)");
            finder.setParam("id", userId);
        }

        finder.setOrder(new Order("createDate", Order.Direction.desc));
        finder.setMaxResults(5);
        return finder.findHQLList();
    }
    @Override

    public Message send(Long id, DeliveryMethodDomain methodDomain, String express) {
        ShopOrderDomain shopOrder  = find(id);
        if(shopOrder.getStatus()!= IntergralOrderStatus.unsend){
            throw new NoticeException("商品状态不是未发货!");
        }
        shopOrder.setDeliveryMethod(methodDomain);
        shopOrder.setExpress(express);
        shopOrder.setStatus(IntergralOrderStatus.send);
        persist(shopOrder);
        return Message.success("操作成功", null);
    }

    @Override
    public Message received(Long id) {
        ShopOrderDomain shopOrder  = find(id);
        if(shopOrder.getStatus()!= IntergralOrderStatus.send){
          //  if(orderItem == null) {
                throw new NoticeException("商品状态不是已发货!");
           // }
        }
        shopOrder.setStatus(IntergralOrderStatus.received);

        return Message.success("操作成功",null);
    }




    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Override
    public void createOrder(Long currStoreId, Long memberId, Long[] cartItemIds, String name, String phone, String address,Long store) {
        if (cartItemIds == null) {
            throw new NoticeException("购买积分商品不存在");
        }

        if (memberId == null) {
            throw new NoticeException("会员不存在");
        }
        MemberDomain member = memberDao.find(memberId);
        if (member == null) {
            throw new NoticeException("会员不存在");
        }

        Finder finder = Finder.create("from ShopCartItemDomain bean where bean.cart.member.id = :memberId and bean.id in (:itemIds)");
        finder.setParam("memberId", memberId);
        finder.setParamList("itemIds", cartItemIds);
        List<ShopCartItemDomain> list = finder.findHQLList();
        if (list.size() < cartItemIds.length) {
            throw new NoticeException("购买商品有部分不在购物车中");
        }
        for (ShopCartItemDomain item : list) {
            shopCartItemDao.lock(item, LockModeType.PESSIMISTIC_WRITE);
            IntergralShopOrderBean bean = new IntergralShopOrderBean();
            bean.setAddress(address);
            bean.setName(name);
            bean.setNum(item.getNum());
            bean.setStoreId(store);
            bean.setPhone(phone);
            bean.setMemberId(memberId);
            bean.setProductId(item.getProduct().getId());
            exchange(bean);
            //删除购物车项
            shopCartItemDao.remove(item);
        }
    }
}





